package com.xmb.wcapi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmb.wcapi.constant.DepConstant;
import com.xmb.wcapi.constant.MaterialTypeConstant;
import com.xmb.wcapi.dto.ApiBomVo;
import com.xmb.wcapi.entity.*;
import com.xmb.wcapi.mapper.BaseMaterialMapper;
import com.xmb.wcapi.mapper.IOSReportMapper;
import com.xmb.wcapi.mapper.IOSReportWorkMapper;
import com.xmb.wcapi.mapper.SysConfigMapper;
import com.xmb.wcapi.service.IIOSReportService;
import com.xmb.wcapi.util.ShiroUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author huangping
 * @since 2024-04-12
 */
@Service
public class IOSReportServiceImpl extends ServiceImpl<IOSReportMapper, IOSReport> implements IIOSReportService {

    @Autowired
    private BaseMaterialMapper baseMaterialMapper;

    @Autowired
    private IOSReportMapper iosReportMapper;

    @Autowired
    private IOSReportWorkMapper iosReportWorkMapper;
    @Autowired
    private ShiroUtil shiroUtil;

    @Override
    public IPage<IOSReportDetails> selectInfoPage(Page<?> page, String cusCode, String material) {
        QueryWrapper<IOSReport> ew = new QueryWrapper<>();
        ew.eq("cCusCode",cusCode);
        ew.eq(StringUtils.isNotEmpty(material),"cInvCode",material);
        ew.orderByAsc("cInvCode");//要添加排序 page分页才有效果
        IPage<IOSReportDetails> iPage = iosReportMapper.selectInfo(page, ew);
        if (!iPage.getRecords().isEmpty()){
            extracted(iPage.getRecords());
        }
        return iPage;
    }

    private void extracted(List<IOSReportDetails> records) {
        //查询 details
        Set<String> set = records.stream().map(IOSReportDetails::getMaterial).collect(Collectors.toSet());
        if (!set.isEmpty()){
            QueryWrapper<IOSReportWork> ewWork = new QueryWrapper<>();
            ewWork.in("a.StrGoodsCode",set);
            List<IOSReportWork> works = iosReportWorkMapper.selectInfo(ewWork);
            if (!works.isEmpty()){
                Map<String, List<IOSReportWork>> listMap = works.stream().collect(Collectors.groupingBy(IOSReportWork::getStrGoodsCode));
                for (IOSReportDetails details : records) {
                    //正常情况一个 料号
                    IOSReportWork work = listMap.get(details.getMaterial()).get(0);
                    details.setOrderNumber(work.getLngWorkLoadNo());
                    details.setQuantity(work.getDblQu());
                    details.setProductionDateStart(work.getStrKGRQ());
                    details.setProductionDateEnd(work.getStrWGRQ());
                    details.setSuitQuantity(work.getDblOutQu());
                    details.setReceivedQuantity(work.getDblTotalInQu());
                    details.setSums(work.getSums());
                    details.setProduct(work.getProduct());

                    //未结工单 (计划-完结-废品)
                    BigDecimal divide = new BigDecimal(work.getDblQu())
                            .subtract(new BigDecimal(work.getDblTotalInQu()))
                            .subtract(new BigDecimal(work.getDblTotalFPQu()));
                    details.setOutstandingMonad(divide.toPlainString());

                }
            }
        }
    }

    @Override
    public List<ApiBomVo> selectAllDom(String cusCode) {
        //查询成品
        List<BaseMaterial> list = baseMaterialMapper.selectList(Wrappers.lambdaQuery(BaseMaterial.class)
                .eq(BaseMaterial::isChecked,true).eq(BaseMaterial::getClassType,"A")
        );

        List<ApiBomVo> allBomList = new ArrayList<>();

        //查询当前产成品下面
        for (BaseMaterial baseMaterial : list) {
            List<BaseMaterial> materialList = new ArrayList<>();
            extracted(materialList,baseMaterial.getLevels(),baseMaterial.getBomId(),baseMaterial.getAllComponentId());

            //层级分组
            Map<String, List<BaseMaterial>> collect = materialList.stream().collect(Collectors.groupingBy(BaseMaterial::getParentBomId));
            BaseMaterial mater = baseMaterial;
            boolean mark = true;
            while (mark){
                List<BaseMaterial> baseMaterials = collect.get(mater.getBomId());
                if (baseMaterials == null){
                    mark = false;
                } else {
                    for (BaseMaterial ma : baseMaterials) {
                        ApiBomVo bom = new ApiBomVo();
                        bom.setVendorCode("620425");
                        //主阶bom信息 start
                        bom.setBmb01(mater.getDjMaterial());
                        if (StringUtils.isEmpty(mater.getCusMaterial())){
                            for (DepConstant value : DepConstant.values()) {
                                if (mater.getDjMaterial().contains(value.getCode())){
                                    bom.setIma021m(value.getMessage());
                                }else {
                                    if (mater.getMaterialMrk().contains(value.getMessage())){
                                        bom.setIma021m(value.getMessage());
                                    }
                                }
                            }
                        }else {
                            bom.setIma021m(mater.getCusMaterial());
                        }
                        bom.setIma02m(mater.getMaterialMrk());

                        //下阶bom信息 start
                        bom.setBmb03(ma.getDjMaterial());
                        bom.setIma021(ma.getCusMaterial());
                        for (DepConstant value : DepConstant.values()) {
                            if (ma.getDjMaterial().contains(value.getCode())){
                                bom.setIma021(value.getMessage());
                            }else {
                                if (ma.getMaterialMrk().contains(value.getMessage())){
                                    bom.setIma021(value.getMessage());
                                }
                            }
                        }
                        bom.setIma02(ma.getMaterialMrk());
                        bom.setQpa(ma.getBaseQty());
                        if (ma.getClassType().equals(MaterialTypeConstant.B.code) || ma.getClassType().equals(MaterialTypeConstant.A.code)){
                            bom.setMaterialType(MaterialTypeConstant.getMessage(ma.getClassType()));
                        }else {
                            //只要不是制程，成品，其他的都是 辅料
                            bom.setMaterialType(MaterialTypeConstant.C.message);
                        }
                        allBomList.add(bom);
                        if (ma.getClassType().equals(MaterialTypeConstant.B.code)){
                            mater = ma;
                        }
                    }
                }
            }
        }
        return allBomList;
    }

    private void extracted(List<BaseMaterial> allList,int lev,String bomId,String allBomId) {
        List<BaseMaterial> records = baseMaterialMapper.selectPage(new Page<>(1,1),Wrappers.lambdaQuery(BaseMaterial.class)
                .eq(BaseMaterial::isChecked, true)
                .eq(BaseMaterial::getAllComponentId,allBomId)
                .gt(BaseMaterial::getLevels, lev)
                .orderByAsc(BaseMaterial::getLevels)
        ).getRecords();
        if (null != records && !records.isEmpty()){
            BaseMaterial material = records.get(0);
            records = baseMaterialMapper.selectList(Wrappers.lambdaQuery(BaseMaterial.class)
                    .eq(BaseMaterial::isChecked, true)
                    .eq(BaseMaterial::getAllComponentId,allBomId)
                    .eq(BaseMaterial::getLevels, material.getLevels())
            );
            for (BaseMaterial record : records) {
                record.setParentBomId(bomId);
                allList.add(record);
                //是否包含半成品
                if (record.getClassType().equals(MaterialTypeConstant.B.code)){
                    bomId = record.getBomId();
                }
            }
            extracted(allList,material.getLevels(),bomId,allBomId);
        }
    }

    public IPage<IOSReportDetails> selectInfoTreePage(String cusCode, String material, String cInvDefine9){
        QueryWrapper<IOSReport> ew = new QueryWrapper<>();
        ew.eq("cCusCode",cusCode);
        ew.eq(StringUtils.isNotEmpty(material),"cInvCode",material);
        ew.isNotNull("ModifyDate");
        ew.eq(StringUtils.isNotEmpty(cInvDefine9),"aa.cInvDefine9",cInvDefine9);
        ew.orderByAsc("cInvCode");//要添加排序 page分页才有效果
        IPage<IOSReport> iPage = iosReportMapper.selectInfoTreePage(new Page<>(-1,-1), ew);
        List<IOSReportDetails> iosReportDetails = new ArrayList<>();
        // 第一次 BOM 母件
        for (IOSReport record : iPage.getRecords()) {
            IOSReportDetails details = new IOSReportDetails();
            details.setMaterial(record.getMaterial());
            details.setMaterialName(record.getMaterialName());
            details.setComponentId(record.getBomId());
            details.setParentBomId("0");
            iosReportDetails.add(details);
            extractedPage(record,iosReportDetails);
        }
        IPage<IOSReportDetails> detailsPage = new Page<>();
        detailsPage.setTotal(iosReportDetails.size());
        List<List<IOSReportDetails>> split = ListUtil.split(iosReportDetails, 2);
        for (List<IOSReportDetails> details : split) {
            //获取子件详细信息
            extracted(details);
        }
        detailsPage.setRecords(iosReportDetails);
        return detailsPage;
    }

    private void extractedPage(IOSReport reportDe, List<IOSReportDetails> iosReportDetails) {
        boolean mark = false;
        if (StringUtils.isNotEmpty(reportDe.getBomId())){
            //子件
            List<IOSReportDetails> details = iosReportMapper.selectSon(reportDe.getBomId());
            //获取子件详细信息
            extracted(details);
            for (IOSReportDetails reportDetails : details) {
                // B=制程，D=原料,C=辅料
                reportDetails.setMaterialTypeName(MaterialTypeConstant.getMessage(reportDetails.getMaterialType()));
                reportDetails.setMaterial(reportDetails.getProduct());
                reportDetails.setMaterialName(reportDetails.getMaterialName());
                //bom 和 审核时间不为空 代表有下一级 一般只有一条有效数据
                if (StringUtils.isNotEmpty(reportDetails.getBomId()) && StringUtils.isNotEmpty(reportDetails.getModifyDate())){
                    reportDe.setBomId(reportDetails.getBomId());
                    reportDetails.setComponentId(reportDetails.getBomId());
                    //当前条也算是子件
                    iosReportDetails.add(reportDetails);
                    mark = true;
                }
                //bom为空就是当前级的子项
                if (StringUtils.isEmpty(reportDetails.getBomId())){
                    iosReportDetails.add(reportDetails);
                }
            }
        }
        //此处递归
        if (mark){
            //调用自身
            extractedPage(reportDe,iosReportDetails);
        }
    }

}
